package com.simafei.flow.core.data.ds;

import cn.hutool.core.util.StrUtil;

import java.util.function.Supplier;

/**
 * @author fengpengju
 */
public class DataSourceExecutor {
    public static void run(Runnable runnable, String dsName) {
        String origin = FlowDataSourceContextHolder.get();

        try {
            FlowDataSourceContextHolder.set(dsName);

            runnable.run();
        } finally {
            if (StrUtil.isNotEmpty(origin)) {
                FlowDataSourceContextHolder.set(origin);
            } else {
                FlowDataSourceContextHolder.clear();
            }
        }

    }

    public static <T> T call(Supplier<T> supplier, String dsName) {
        String origin = FlowDataSourceContextHolder.get();

        try {
            FlowDataSourceContextHolder.set(dsName);
            return supplier.get();
        } finally {
            if (StrUtil.isNotEmpty(origin)) {
                FlowDataSourceContextHolder.set(origin);
            } else {
                FlowDataSourceContextHolder.clear();
            }
        }

    }
}
